from django.shortcuts import render
from django.http import JsonResponse
from django.db import connection
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from .models import ScoreDetail, ScoreRank
from .utils import dictfetchall


# Create your views here.

@csrf_exempt
def search_(request):
    """
    查询排行榜
    :param request:
    :return:
    """
    name = request.GET.get('name', None)
    start_ = request.GET.get('start_', 1)
    end_ = request.GET.get('end_', 10)
    meta = {'msg': '成功查询', 'data': [], 'code': 200}
    if not name:
        meta['msg'] = '缺少参数'
        meta['code'] = 400
        return JsonResponse(meta, safe=False)
    if isinstance(start_, str) or isinstance(end_, str):
        try:
            start_ = int(start_)
            end_ = int(end_)
        except Exception as e:
            meta['msg'] = '数据格式不正确'
            meta['code'] = 400
            return JsonResponse(meta, safe=False)
    with connection.cursor() as cursor:
        limit = " limit %(start_index)s, %(end_index)s"
        params_dict = {'start_index': int(start_) - 1, 'end_index': int(end_)}
        sql = " select name, Max(score) as score  from score_scoredetail group by name order by score desc {limit} ".format(
            limit=limit)
        cursor.execute(sql, params=params_dict)
        result = dictfetchall(cursor)
    index_ = 0
    for row in result:
        index_ += 1
        row['index'] = index_
    all_data = ScoreDetail.objects.all().values('name', 'score').order_by('-score')
    index_2 = 0
    for row in all_data:
        index_2 += 1
        if name == row['name']:
            result.append({'name': name, 'score': row['score'], 'index': index_2})
            break
    meta['data'] = result
    print(result)
    return JsonResponse(meta, safe=False)


def client(request):
    pass
    return render(request, 'client.html')


@csrf_exempt
def upload_data(request):
    """
    上传数据
    :param request:
    :return:
    """
    name = request.POST.get('name', None)
    score = request.POST.get('score', None)
    meta = {'msg': '上传成功', 'data': [], 'code': 200}
    if not (name and score):
        meta['msg'] = '缺少参数'
        meta['code'] = 400
        return JsonResponse(meta, safe=False)
    if isinstance(score, str):
        try:
            score = int(score)
        except Exception as e:
            meta['msg'] = '数据格式不正确'
            meta['code'] = 400
            return JsonResponse(meta, safe=False)
    defaults = {'score': int(score)}
    ScoreDetail.objects.update_or_create(name=name, defaults=defaults)
    meta['msg'] = '上传成功'
    return JsonResponse(meta, safe=False)
